package com.wyj.code.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wyj.code.api.ICodeApi;
import com.wyj.code.entity.dto.CodeDTO;
import com.wyj.code.entity.po.CodePO;
import com.wyj.code.mapper.ICodeMapper;
import com.wyj.code.service.ICodeApiImpl;
import com.wyj.response.ApiResult;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * TODO:
 *
 * @author wuyijie
 * @date 2022/2/9 23:44
 */

@RestController
@Slf4j
public class CodeController implements ICodeApi {
    private final ICodeApiImpl iCodeApi;
    private final ICodeMapper iCodeMapper;

    public CodeController(ICodeApiImpl iCodeApi, ICodeMapper iCodeMapper) {
        this.iCodeApi = iCodeApi;
        this.iCodeMapper = iCodeMapper;
    }

    /**
     * TODO: 根据唯一标识创建code
     *
     * @param identification 唯一标识
     * @return com.wyj.resoponse.ApiResult<com.wyj.code.entity.dto.CodeDTO>
     * @author wuyijie
     * @date 2022/2/10 5:30 PM
     */
    @Override
    public ApiResult<CodeDTO> createWithIdentification(String identification) {
        final CodePO code = new CodePO();
        final String s = iCodeApi.create(identification);
        code.setCode(s);
        code.setIdentification(identification);
        final LocalDateTime now = LocalDateTime.now();
        final LocalDateTime localDateTime = now.plusMinutes(2);
        code.setDeadline(localDateTime);
        final LocalDateTime begin = LocalDateTime.now();
        iCodeMapper.insert(code);
        final LocalDateTime end = LocalDateTime.now();
        final Duration between = Duration.between(begin, end);
        final long l = between.toMillis();
        log.info("createWithIdentification 插入数据库耗时：{}", l);
        return ApiResult.ok(code.convert());
    }

    /**
     * TODO: 根据验证码、标识，查询验证码信息
     *
     * @param code           验证码
     * @param identification 标识
     * @return com.wyj.resoponse.ApiResult<com.wyj.code.entity.dto.CodeDTO>
     * @author wuyijie
     * @date 2022/2/10 6:38 PM
     */
    @Override
    public ApiResult<CodeDTO> code(String code, String identification) {
        final LambdaQueryWrapper<CodePO> lambdaQueryWrapper = new LambdaQueryWrapper<CodePO>().eq(CodePO::getCode, code).eq(CodePO::getIdentification, identification);
        final CodePO codePo = iCodeMapper.selectOne(lambdaQueryWrapper);
        return ApiResult.ok(codePo.convert());
    }
}
